package com.elong.android.specialhouse.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

public class AutoAdjustTextView extends TextView {
	public final static int MIN_TEXTSIZE = 15;
	private float m_originalTextSize;

	public AutoAdjustTextView(Context context, AttributeSet attrs) {
		super(context, attrs);

		m_originalTextSize = getTextSize();

		m_originalTextSize = (m_originalTextSize / context.getResources().getDisplayMetrics().scaledDensity);

	}

	public void onDraw(Canvas canvas) {
		float textSize = adjustTextSize(canvas);
		if (textSize <= MIN_TEXTSIZE) {
			setSingleLine();
		}
		setTextSize(textSize);
		super.onDraw(canvas);
	}

	public float adjustTextSize(Canvas canvas) {
		if (getText() == null) {
			return m_originalTextSize;
		}

		String text = getText().toString();

		if (!TextUtils.isEmpty(text)) {
			int w = this.getWidth();
			int textSize = (int) m_originalTextSize;
			Paint p = new Paint();
			p.setTextSize(textSize);

			while (p.measureText(text) > w) {
				textSize--;
				if (textSize <= MIN_TEXTSIZE) {
					break;
				}
				p.setTextSize(textSize);
			}
			return textSize;
		}
		return m_originalTextSize;
	}
}
